// 导入数据库模块
const db = require("../db/index.js");

// 获取用户数据
exports.getUserInfo = (req, res) => {
    const pageNo = req.query.pageNo
    const pageSize =  Number(req.query.pageSize)
    const key = req.query.key
    const startIndex = (pageNo - 1) * pageSize
    const sql = `select * from users`
    // console.log(pageNo, pageSize, key);
    db.query(sql, (err, result) => {
        if (err) {
            throw Error("Server Error");
        }
        let data = null
        let resultData = JSON.parse(JSON.stringify(result))

        resultData.forEach(item => {
            Object.keys(item).forEach(key => {
                if (key === 'is_admin') {
                    item[key] = item[key] === 0 ? '否' : '是'
                }
                if (key === 'sex') {
                    item[key] = (item[key] === null || item[key] === '')  ?'未知': item[key] 
                }
                if (key === 'signature') {
                    item[key] = (item[key] === null || item[key] === '') ? '无' : item[key]
                }
            })
        })

        if (!key) {
            data = resultData.slice(startIndex, startIndex + pageSize)

        } else {
            data = resultData.filter(item => (item.user_id.includes(key) || item.email.includes(key)))
                .slice(startIndex, startIndex + pageSize)
        }
        // console.log(data);
        res.send({
            code: 200,
            data: {
                dataLength: result.length,
                data,
                result
            }
        })
    })
}

// 获取角色数据
exports.getRoleInfo = (req, res) => {
    const pageNo = req.query.pageNo
    const pageSize =  Number(req.query.pageSize)
    const startIndex = (pageNo - 1) * pageSize
    const sql = `select * from role`
    db.query(sql, (err, result) => {
        if (err) {
            throw Error("Server Error");
        }
        let data = null
        let resultData = JSON.parse(JSON.stringify(result))

        resultData.forEach(item => {
            Object.keys(item).forEach(key => {
                if (key === 'des') {
                    item[key] = (item[key] === null || item[key] === '' || item[key] === undefined)  ? '无' :  item[key]
                }
            })
        })

       
       data = resultData.slice(startIndex, startIndex + pageSize)

      
        res.send({
            code: 200,
            data: {
                dataLength: result.length,
                data,
                result
            }
        })
    })
}


// 增加用户信息
exports.addUserInfo = (req, res) => {
    const sql = `select * from users where user_id = ?`
    const insertSql = `insert into users(user_id,PASSWORD,email,sex,head,money_code,signature,is_admin)values(?,?,?,?,?,?,?,?)`
    db.query(sql, req.body.user_id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        if (result.length >= 1) {
            return res.send({
                code: 500,
                message: '该用户已存在'
            })
        }
        db.query(insertSql, [req.body.user_id, req.body.password, req.body.email, req.body.sex, req.body.head,
        req.body.money_code, req.body.signature, req.body.is_admin], (err, result) => {
            if (err) {
                throw Error('Server Error')
            }
            res.send({
                code: 200,
                message: '创建成功'
            })
        })
    })
}

// 更新用户信息
exports.updateUserInfo = (req, res) => {
    const sql = `update users set user_id = ?,password = ?,email = ?,sex = ?,head = ?,money_code = ?,
    signature = ?,is_admin = ? where id = ?`
    db.query(sql, [req.body.user_id, req.body.password, req.body.email, req.body.sex, req.body.head,
    req.body.money_code, req.body.signature, req.body.is_admin, req.body.id], (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
            message: '更新成功'
        })
    })
}

// 删除用户信息
exports.deleteUserInfo = (req, res) => {
    const sql = `delete from users where id = ?`
    db.query(sql, req.query.id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
            message: '删除成功'
        })
    })
}


// 获取所有角色
exports.getAllRole = (req,res) => {
    const sql = `select * from ROLE`
    db.query(sql, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
            data:result
        })
    })
}

// 根据用户id获取用户角色
exports.getUserRole = (req,res) => {
    const sql = `select * from user_role where user_id = ?`
    // console.log(req.query.user_id);
    db.query(sql,req.query.user_id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
            data:result
        })
    })
}

// 获取权限
exports.getUserMenu = (req,res) => {
    const sql = `
    SELECT rp.permission_id,p.permission_name,ur.user_id
    FROM role_permission rp
    LEFT JOIN permission p
    ON rp.permission_id = p.permission_id
    LEFT JOIN user_role ur
    ON ur.role_id = rp.role_id
    WHERE ur.user_id = ?`
    // console.log(req.query.user_id);
    db.query(sql,req.query.user_id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
            data:result
        })
    })
}

// 根据用户id删除对应的角色
exports.deleteRoleByUserId = (req,res) => {
    const deleteSql = `delete from user_role where user_id = ?`
    db.query(deleteSql,req.query.user_id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
        })
    })
}

/**
 * 根据角色id删除对应的权限
 * @param {*} req 
 * @param {*} res 
 */
exports.deleteAuthByRoleId = (req,res) => {
    const deleteSql = `delete from role_permission where role_id = ?`
    db.query(deleteSql,req.query.role_id, (err, result) => {
        if (err) {
            throw Error('Server Error')
        }
        res.send({
            code: 200,
        })
    })
}

// 根据角色id添加权限
exports.addAuthByRoleId = (req,res) => {
    const auth = req.body.auth
    const insertSql = `insert into role_permission(role_id,permission_id)values(?,?)`
    auth.forEach(item => {
        db.query(insertSql,[req.body.role_id,item],(err) => {
            if(err){
                throw Error('Server Error')
            }
        })
    })
    res.send({
        code:200,
        message:'分配权限成功'
    })
   
}

// 根据用户id添加角色
exports.addRolesByUserId = (req,res) => {
    const roles = req.body.roles
    const insertSql = `insert into user_role(user_id,role_id)values(?,?)`
    roles.forEach(item => {
        db.query(insertSql,[req.body.user_id,item],(err) => {
            if(err){
                throw Error('Server Error')
            }
        })
    })
    res.send({
        code:200,
        message:'分配用户角色成功'
    })
   
}

// 增加角色
exports.addRole = (req,res) => {
    const sql = `INSERT INTO ROLE(role_id,role_name,des)VALUES(?,?,?)`
    db.query(sql,[req.body.role_id,req.body.role_name,req.body.des],(err,result) => {
        if(err){
            throw Error('Server Error')
        }
        res.send({
            code:200,
            message:'新增角色成功'
        })
    })
}

// 编辑角色
exports.editRole = (req,res) => {
    const sql = `update ROLE set role_name = ?,des = ? where role_id = ?`
    db.query(sql,[req.body.role_name,req.body.des,req.body.role_id],(err,result) => {
        if(err){
            throw Error('Server Error')
        }
        res.send({
            code:200,
            message:'更新角色成功'
        })
    })
}

// 删除角色
exports.deleteRoleById = (req,res) => {
    const sql = `delete from role where role_id = ?`
    db.query(sql,[req.query.role_id],(err,result) => {
        if(err){
            throw Error('Server Error')
        }
        res.send({
            code:200,
            message:'删除角色成功'
        })
    })
}

// 获取全部权限
exports.getAllAuth = (req,res) => {
    const sql = `select * from permission`
    db.query(sql,(err,result) => {
        if(err){
            throw Error('Server Error')
        }
        let dataResult = JSON.parse(JSON.stringify(result)).map(item => {
            return{
                permission_id:item.permission_id,
                permission_name:item.permission_name
            }
        })

        res.send({
            code:200,
            data:dataResult
        })
    })
}

// 根据角色id获取权限
exports.getAuthByRoleId = (req,res) => {
    const sql = `SELECT p.permission_id,p.permission_name
    FROM role_permission rp
    LEFT JOIN permission p
    ON rp.permission_id = p.permission_id
    WHERE role_id = ?`
    db.query(sql,req.query.role_id,(err,result) => {
        if(err){
            throw Error('Server Error')
        }

        res.send({
            code:200,
            data:result
        })
    })
}